package com.beidouin.sensortest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.HardWare.QMC5883;
import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import static com.HardWare.QMC5883.QMC5883_Init;

public class CompassActivity extends AppCompatActivity implements Runnable{

    TextView comtxv_1,comtxv_2,comtxv_3;
    int devFD=-1;
    Handler handler;
    Thread t = new Thread(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);
        comtxv_1= (TextView) findViewById(R.id.x_mag);
        comtxv_2= (TextView) findViewById(R.id.y_mag);
        comtxv_3= (TextView) findViewById(R.id.z_mag);

        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        QMC5883_Init(devFD);


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x101) {
                    comtxv_1.setText(msg.getData().getDouble("data0")+"Ga");
                    comtxv_2.setText(msg.getData().getDouble("data1")+"Ga");
                    comtxv_3.setText(msg.getData().getDouble("data2")+"Ga");
                }
                super.handleMessage(msg);
            }
        };
        t.start();
    }



    @Override
    protected void onDestroy() {
        //将线程销毁掉
        t.interrupt();
        HardwareControler.close(devFD);
        super.onDestroy();
    }




    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted())
        {
            Message m=handler.obtainMessage();
            double[] data;
            data=new double[3];
            data= QMC5883.get_magnetic(devFD);
            for(int i=0;i<3;i++)
            {
                data[i]= (double)Math.round(data[i]*10000)/10000;
            }
            m.what=0x101;
            Bundle bundle =new Bundle();
            bundle.putDouble("data0",data[0]);
            bundle.putDouble("data1",data[1]);
            bundle.putDouble("data2",data[2]);
            m.setData(bundle);
            handler.sendMessage(m);
            try{
                Thread.sleep(1000);}
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}